"""配置管理模块"""

import os
import yaml
from pathlib import Path
from typing import Dict, Any
from loguru import logger


def load_yaml_file(file_path: Path) -> Dict[str, Any]:
    """加载YAML配置文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f) or {}
    except FileNotFoundError:
        logger.warning(f"配置文件不存在: {file_path}")
        return {}
    except yaml.YAMLError as e:
        logger.error(f"YAML解析错误 {file_path}: {e}")
        raise
    except Exception as e:
        logger.error(f"读取配置文件失败 {file_path}: {e}")
        raise


def load_config(config_dir: str = None) -> Dict[str, Any]:
    """加载所有配置文件"""
    if config_dir is None:
        config_dir = "config"
    
    # 如果是相对路径，则相对于项目根目录
    if not os.path.isabs(config_dir):
        # 从src目录向上一级找到项目根目录
        project_root = Path(__file__).parent.parent
        config_path = project_root / config_dir
    else:
        config_path = Path(config_dir)
    
    if not config_path.exists():
        raise FileNotFoundError(f"配置目录不存在: {config_path}")
    
    # 加载主配置文件
    app_config = load_yaml_file(config_path / "app.yaml")
    database_config = load_yaml_file(config_path / "database.yaml")
    mcp_config = load_yaml_file(config_path / "mcp.yaml")
    
    # 合并配置
    config = {
        **app_config,
        **database_config,
        **mcp_config
    }
    
    # 环境变量覆盖
    config = apply_env_overrides(config)
    
    logger.info("配置加载完成")
    return config


def apply_env_overrides(config: Dict[str, Any]) -> Dict[str, Any]:
    """应用环境变量覆盖"""
    # Redis配置覆盖
    if os.getenv('REDIS_HOST'):
        config.setdefault('databases', {}).setdefault('redis', {})['host'] = os.getenv('REDIS_HOST')
    if os.getenv('REDIS_PORT'):
        config.setdefault('databases', {}).setdefault('redis', {})['port'] = int(os.getenv('REDIS_PORT'))
    if os.getenv('REDIS_PASSWORD'):
        config.setdefault('databases', {}).setdefault('redis', {})['password'] = os.getenv('REDIS_PASSWORD')
    
    # MongoDB配置覆盖
    if os.getenv('MONGODB_HOST'):
        config.setdefault('databases', {}).setdefault('mongodb', {})['host'] = os.getenv('MONGODB_HOST')
    if os.getenv('MONGODB_PORT'):
        config.setdefault('databases', {}).setdefault('mongodb', {})['port'] = int(os.getenv('MONGODB_PORT'))
    if os.getenv('MONGODB_USERNAME'):
        config.setdefault('databases', {}).setdefault('mongodb', {})['username'] = os.getenv('MONGODB_USERNAME')
    if os.getenv('MONGODB_PASSWORD'):
        config.setdefault('databases', {}).setdefault('mongodb', {})['password'] = os.getenv('MONGODB_PASSWORD')
    
    # Neo4j配置覆盖
    if os.getenv('NEO4J_URI'):
        config.setdefault('databases', {}).setdefault('neo4j', {})['uri'] = os.getenv('NEO4J_URI')
    if os.getenv('NEO4J_USERNAME'):
        config.setdefault('databases', {}).setdefault('neo4j', {})['username'] = os.getenv('NEO4J_USERNAME')
    if os.getenv('NEO4J_PASSWORD'):
        config.setdefault('databases', {}).setdefault('neo4j', {})['password'] = os.getenv('NEO4J_PASSWORD')
    
    # ChromaDB配置覆盖
    if os.getenv('CHROMADB_HOST'):
        config.setdefault('databases', {}).setdefault('chromadb', {})['host'] = os.getenv('CHROMADB_HOST')
    if os.getenv('CHROMADB_PORT'):
        config.setdefault('databases', {}).setdefault('chromadb', {})['port'] = int(os.getenv('CHROMADB_PORT'))
    
    # HTTP服务器配置覆盖
    if os.getenv('HTTP_HOST'):
        config.setdefault('mcp', {}).setdefault('http', {})['host'] = os.getenv('HTTP_HOST')
    if os.getenv('HTTP_PORT'):
        config.setdefault('mcp', {}).setdefault('http', {})['port'] = int(os.getenv('HTTP_PORT'))
    
    # WebSocket服务器配置覆盖
    if os.getenv('WS_HOST'):
        config.setdefault('mcp', {}).setdefault('websocket', {})['host'] = os.getenv('WS_HOST')
    if os.getenv('WS_PORT'):
        config.setdefault('mcp', {}).setdefault('websocket', {})['port'] = int(os.getenv('WS_PORT'))
    
    return config


def get_database_url(config: Dict[str, Any], db_type: str) -> str:
    """获取数据库连接URL"""
    db_config = config.get('databases', {}).get(db_type, {})
    
    if db_type == 'redis':
        host = db_config.get('host', 'localhost')
        port = db_config.get('port', 6379)
        db = db_config.get('db', 0)
        password = db_config.get('password')
        
        if password:
            return f"redis://:{password}@{host}:{port}/{db}"
        else:
            return f"redis://{host}:{port}/{db}"
    
    elif db_type == 'mongodb':
        host = db_config.get('host', 'localhost')
        port = db_config.get('port', 27017)
        database = db_config.get('database', 'memory_ai')
        username = db_config.get('username')
        password = db_config.get('password')
        
        if username and password:
            return f"mongodb://{username}:{password}@{host}:{port}/{database}"
        else:
            return f"mongodb://{host}:{port}/{database}"
    
    elif db_type == 'neo4j':
        return db_config.get('uri', 'bolt://localhost:7687')
    
    elif db_type == 'chromadb':
        host = db_config.get('host', 'localhost')
        port = db_config.get('port', 8000)
        return f"http://{host}:{port}"
    
    else:
        raise ValueError(f"不支持的数据库类型: {db_type}")